import 'dart:async';

import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/smart_warehouse/warehousing_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/smart_warehouse/common_warehouse/new_add_product_dialog.dart';
import 'package:enterprise_v6_app/app/modules/application/smart_warehouse/product_outbound/product_outbound_controller.dart';
import 'package:enterprise_v6_app/app/modules/application/smart_warehouse/product_storage/product_storage_controller.dart';

/// 出入库页面-连接状态时显示的页面
/// [type]] 出入库类型 0:入库 1:出库
/// [warehouseName] 仓库名称
/// [warehouseId] 仓库id
class WarehouseConnectionWidget extends StatefulWidget {
  const WarehouseConnectionWidget({
    required this.type,
    required this.warehouseId,
    super.key,
    this.warehouseName,
  });

  final int type; // 出入库类型 0:入库 1:出库
  final String? warehouseName; // 仓库名称
  final String? warehouseId; // 仓库id

  @override
  State<WarehouseConnectionWidget> createState() => _WarehouseConnectionWidgetState();
}

class _WarehouseConnectionWidgetState extends State<WarehouseConnectionWidget> {
  /// 算法出入库数量列表数据
  List<WarehousingEntity> productList = [];

  /// 定时器
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    _getProductList();
  }

  @override
  void dispose() {
    super.dispose();
    _timer.cancel();
  }

  /// 获取出入库列表数据
  _getProductList() async {
    // 每秒执行一次获取出入库数量列表数据
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) async {
      final res = await HttpUtil().generateGetRequest<List<WarehousingEntity>>(
        Interface.getInventoryList,
        queryParameters: {'outboundOrInbound': widget.type},
      ).execute();
      res.onSuccess((result) {
        if (result.data != null) {
          productList = result.data!;
          // productList = [
          //   WarehousingEntity()
          //     ..id = '1244'
          //     ..createDate = '2023-03-17 10:20:00'
          //     ..receiptQuantity = 10,
          //   WarehousingEntity()
          //     ..id = '1'
          //     ..createDate = '2023-03-17 10:20:00'
          //     ..receiptQuantity = 9,
          //   WarehousingEntity()
          //     ..id = '2'
          //     ..createDate = '2023-03-17 10:20:00'
          //     ..receiptQuantity = 8,
          // ];
          setState(() {});
        }
      });
    });
  }

  ///刷新按钮
  Widget _getEndButton() {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xff5C6DFF),
        borderRadius: BorderRadius.all(Radius.circular(8.w)),
      ),
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.w),
      child: Text(
        '结束',
        style: TextStyle(height: 1.2, color: const Color(0xffffffff), fontSize: 14.w, fontWeight: FontWeight.w400),
      ),
    ).clickOnce(() {
      if (widget.type == 0) {
        final taskController = Get.find<ProductStorageController>();
        taskController.executionCompletion();
      } else {
        final taskController = Get.find<ProductOutboundController>();
        taskController.executionCompletion();
      }
    });
  }

  /// 获取产品标题显示
  Widget _getProductTitleWidget() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 10.w),
      decoration: BoxDecoration(
        color: const Color(0xffEEF0FF),
        borderRadius: BorderRadius.all(Radius.circular(8.w)),
      ),
      child: Row(
        children: [
          Expanded(
              child: Text(
            '数量',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontWeight: FontWeight.w500,
              fontSize: 12.w,
              color: const Color(0xff5C6DFF),
            ),
          )),
          Expanded(
              child: Text(
            '时间',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontWeight: FontWeight.w500,
              fontSize: 12.w,
              color: const Color(0xff5C6DFF),
            ),
          )),
        ],
      ),
    );
  }

  ///获取产品列表
  Widget _getProductListView(WarehousingEntity product) {
    return Container(
      constraints: BoxConstraints(
        minHeight: 30.w,
      ),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                  child: Text(
                product.receiptQuantity.toString(),
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontWeight: FontWeight.w400,
                  fontSize: 12.w,
                  color: const Color(0xff818499),
                ),
              )),
              Expanded(
                  child: Text(
                product.createDate.toString(),
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontWeight: FontWeight.w400,
                  fontSize: 12.w,
                  color: const Color(0xff818499),
                ),
              )),
            ],
          ),
          Container(
            height: 1.w,
            color: const Color(0xffF2F2F2),
            margin: EdgeInsets.symmetric(vertical: 12.w),
          ),
        ],
      ),
    ).clickOnce(() {
      Get.dialog(NewAddProductDialog(
        num: product.receiptQuantity,
        type: widget.type,
        warehouseId: widget.warehouseId ?? '',
        id: product.id,
      ));
    });
  }

  ///获取产品列表
  Widget _getProductListWidget() {
    return Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(color: const Color(0xffffffff), borderRadius: BorderRadius.all(Radius.circular(8.w))),
        padding: EdgeInsets.all(10.w),
        child: Column(
          children: [
            _getProductTitleWidget(),
            AppGaps.vGap20,
            Expanded(
              child: ListView.builder(
                itemCount: productList.length,
                itemBuilder: (BuildContext context, int index) {
                  return _getProductListView(productList[index]);
                },
              ),
            ),
          ],
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          children: [
            Expanded(
                child: Container(
              alignment: Alignment.centerLeft,
              decoration: BoxDecoration(color: const Color(0xffffffff), borderRadius: BorderRadius.all(Radius.circular(8.w))),
              padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 8.w),
              child: Text(
                widget.warehouseName ?? '',
                style: TextStyle(height: 1.2, color: const Color(0xffA0A7B5), fontSize: 14.w, fontWeight: FontWeight.w400),
              ),
            )),
            AppGaps.hGap10,
            _getEndButton()
          ],
        ),
        AppGaps.vGap16,
        Expanded(child: _getProductListWidget()),
        AppGaps.vGap16,
        // _getBottomButtonView()
      ],
    );
  }
}
